#include "PhysicsTest.h"

#include "InputHandler.h"
#include "Utility.h"
#include "GameGlobals.h"
#include "Resources.h"

LINKCLASSTONAME("ent_physics", PhysicsTest);

PhysicsTest::PhysicsTest(sf::RenderWindow *App) : BaseMoveable(App)
{
	DrawOrder = 0;

	sf::Vector2f Points[4];
	float height, width;
	height = Util::Random(50,200);
	width = Util::Random(50,200);
	height = 64;
	width = 64;
	Points[0] = sf::Vector2f(-width / 2,height / 2);
	Points[1] = sf::Vector2f(width / 2, height / 2);
	Points[2] = sf::Vector2f(width / 2, -height / 2);
	Points[3] = sf::Vector2f(-width / 2, -height / 2);

	CreatePhysics();
	GetPhysicsObject()->PhysicsInitPolygon(this, Points, 4);
	GetPhysicsObject()->SetMass((width * height) / 100);

	sf::Vector2<float> Pos(Util::Random(-300,300),400);
	GetPhysicsObject()->SetPos(Pos);
	SetPos(Pos);

	shpHull.SetTexture(*Resources::Instance()->RequestImage("crate"));
	shpHull.Resize(width + 4,height + 4);
	shpHull.SetOrigin(128,128);
	shpHull.SetPosition(GetSFMLPos());

}

PhysicsTest::~PhysicsTest(void)
{
}

void PhysicsTest::Think()
{
	float delta = GameGlobals::Instance()->FrameTime;
	if (InputHandler::IsMouseButtonPressed(sf::Mouse::Left))
	{
		GetPhysicsObject()->ApplyForceOffset(Util::VecScale(InputHandler::GetMousePosWorld(*pRender) - GetPos(), GetPhysicsObject()->GetMass() / 10.f), sf::Vector2f(0,0));
	}
	if (InputHandler::IsKeyPressed(sf::Keyboard::R))
	{
		GetPhysicsObject()->SetPos(0,-100);
		SetVelocity(0,0);
		GetPhysicsObject()->SetAngle(90);
		GetPhysicsObject()->SetAngularVel(Util::Random(15,20));
	}
	//std::cout << "Y Changed: " << Util::VecScale(GetPhysicsObject()->GetVelocity(), delta).y << "\n";
	GetPhysicsObject()->ApplyForceOffset(sf::Vector2f(0,-10 * GetPhysicsObject()->GetMass()), sf::Vector2f(0,0));
}

void PhysicsTest::Draw()
{
	shpHull.SetPosition(GetSFMLPos());
	shpHull.SetRotation(GetAngle());
	pRender->Draw(shpHull);
	GetPhysicsObject()->Draw();
}